package com.rickpan.service.impl;

import com.rickpan.entity.Note;
import com.rickpan.repository.NoteRepository;
import com.rickpan.service.NoteService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

/**
 * 便签服务实现
 * 
 * @author RickPan Team
 * @since 2024-01-06
 */
@Slf4j
@Service
@Transactional
public class NoteServiceImpl implements NoteService {

    @Autowired
    private NoteRepository noteRepository;

    @Override
    public Note createNote(Long userId, String title, String content, String markdownContent, Long folderId) {
        Note note = new Note();
        note.setUserId(userId);
        note.setTitle(title != null ? title : "无标题");
        note.setContent(content);
        note.setMarkdownContent(markdownContent);
        note.setFolderId(folderId);
        note.setIsFavorite(false);
        note.setViewCount(0);
        note.setIsDeleted(false);
        note.setCreatedAt(LocalDateTime.now());
        note.setUpdatedAt(LocalDateTime.now());

        return noteRepository.save(note);
    }

    @Override
    public Note updateNote(Long noteId, Long userId, String title, String content, String markdownContent, Boolean isFavorite) {
        Optional<Note> optionalNote = noteRepository.findByIdAndUserIdAndIsDeletedFalse(noteId, userId);
        if (optionalNote.isPresent()) {
            Note note = optionalNote.get();
            if (title != null) {
                note.setTitle(title);
            }
            if (content != null) {
                note.setContent(content);
            }
            if (markdownContent != null) {
                note.setMarkdownContent(markdownContent);
            }
            if (isFavorite != null) {
                note.setIsFavorite(isFavorite);
            }
            note.setUpdatedAt(LocalDateTime.now());
            return noteRepository.save(note);
        }
        throw new RuntimeException("便签不存在或无权访问");
    }

    @Override
    public boolean deleteNote(Long noteId, Long userId) {
        Optional<Note> optionalNote = noteRepository.findByIdAndUserIdAndIsDeletedFalse(noteId, userId);
        if (optionalNote.isPresent()) {
            Note note = optionalNote.get();
            note.setIsDeleted(true);
            note.setUpdatedAt(LocalDateTime.now());
            noteRepository.save(note);
            return true;
        }
        return false;
    }

    @Override
    public Note getNoteDetail(Long noteId, Long userId) {
        Optional<Note> optionalNote = noteRepository.findByIdAndUserIdAndIsDeletedFalse(noteId, userId);
        if (optionalNote.isPresent()) {
            Note note = optionalNote.get();
            // 增加查看次数
            note.setViewCount(note.getViewCount() + 1);
            return noteRepository.save(note);
        }
        throw new RuntimeException("便签不存在或无权访问");
    }

    @Override
    public Note getNoteById(Long noteId, Long userId) {
        Optional<Note> optionalNote = noteRepository.findByIdAndUserIdAndIsDeletedFalse(noteId, userId);
        if (optionalNote.isPresent()) {
            return optionalNote.get();
        }
        throw new RuntimeException("便签不存在或无权访问");
    }

    @Override
    public Page<Note> getNotes(Long userId, Long folderId, String search, Boolean isFavorite, Boolean hasReminder, Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "updatedAt"));

        if (search != null && !search.trim().isEmpty()) {
            return noteRepository.searchNotes(userId, search.trim(), pageable);
        } else if (Boolean.TRUE.equals(isFavorite)) {
            return noteRepository.findByUserIdAndIsFavoriteTrueAndIsDeletedFalseOrderByUpdatedAtDesc(userId, pageable);
        } else if (Boolean.TRUE.equals(hasReminder)) {
            // 只显示有提醒时间的便签
            return noteRepository.findByUserIdAndReminderTimeIsNotNullAndIsDeletedFalseOrderByUpdatedAtDesc(userId, pageable);
        } else if (folderId != null) {
            return noteRepository.findByUserIdAndFolderIdAndIsDeletedFalseOrderByUpdatedAtDesc(userId, folderId, pageable);
        } else {
            return noteRepository.findByUserIdAndFolderIdIsNullAndIsDeletedFalseOrderByUpdatedAtDesc(userId, pageable);
        }
    }

    @Override
    public List<Note> getRecentNotes(Long userId, Integer limit) {
        return noteRepository.findTop10ByUserIdAndIsDeletedFalseOrderByUpdatedAtDesc(userId);
    }

    @Override
    public List<Note> getFavoriteNotes(Long userId, Integer limit) {
        return noteRepository.findTop10ByUserIdAndIsFavoriteTrueAndIsDeletedFalseOrderByUpdatedAtDesc(userId);
    }

    @Override
    public Note toggleFavorite(Long noteId, Long userId) {
        Optional<Note> optionalNote = noteRepository.findByIdAndUserIdAndIsDeletedFalse(noteId, userId);
        if (optionalNote.isPresent()) {
            Note note = optionalNote.get();
            note.setIsFavorite(!note.getIsFavorite());
            note.setUpdatedAt(LocalDateTime.now());
            return noteRepository.save(note);
        }
        throw new RuntimeException("便签不存在或无权访问");
    }

    @Override
    public Note moveNote(Long noteId, Long userId, Long targetFolderId) {
        Optional<Note> optionalNote = noteRepository.findByIdAndUserIdAndIsDeletedFalse(noteId, userId);
        if (optionalNote.isPresent()) {
            Note note = optionalNote.get();
            note.setFolderId(targetFolderId);
            note.setUpdatedAt(LocalDateTime.now());
            return noteRepository.save(note);
        }
        throw new RuntimeException("便签不存在或无权访问");
    }

    @Override
    public Note copyNote(Long noteId, Long userId, String newTitle) {
        Optional<Note> optionalNote = noteRepository.findByIdAndUserIdAndIsDeletedFalse(noteId, userId);
        if (optionalNote.isPresent()) {
            Note originalNote = optionalNote.get();
            Note newNote = new Note();
            newNote.setUserId(userId);
            newNote.setTitle(newTitle != null ? newTitle : originalNote.getTitle() + " - 副本");
            newNote.setContent(originalNote.getContent());
            newNote.setMarkdownContent(originalNote.getMarkdownContent());
            newNote.setFolderId(originalNote.getFolderId());
            newNote.setIsFavorite(false);
            newNote.setViewCount(0);
            newNote.setIsDeleted(false);
            newNote.setCreatedAt(LocalDateTime.now());
            newNote.setUpdatedAt(LocalDateTime.now());
            return noteRepository.save(newNote);
        }
        throw new RuntimeException("便签不存在或无权访问");
    }

    @Override
    public NoteStats getNoteStats(Long userId) {
        long totalNotes = noteRepository.countByUserIdAndIsDeletedFalse(userId);
        long favoriteNotes = noteRepository.countByUserIdAndIsFavoriteTrueAndIsDeletedFalse(userId);
        // 今日便签数量（简化实现）
        long todayNotes = 0;

        return new NoteStats(totalNotes, favoriteNotes, todayNotes);
    }

    @Override
    public String exportNoteToMarkdown(Long noteId, Long userId) {
        log.info("开始导出便签: noteId={}, userId={}", noteId, userId);

        Optional<Note> optionalNote = noteRepository.findByIdAndUserIdAndIsDeletedFalse(noteId, userId);
        if (!optionalNote.isPresent()) {
            log.error("便签不存在或无权访问: noteId={}, userId={}", noteId, userId);
            throw new RuntimeException("便签不存在或无权访问");
        }

        Note note = optionalNote.get();
        log.info("找到便签: title={}, contentLength={}", note.getTitle(),
                note.getContent() != null ? note.getContent().length() : 0);

        StringBuilder markdown = new StringBuilder();

        // 添加标题
        markdown.append("# ").append(note.getTitle()).append("\n\n");

        // 添加元数据
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        markdown.append("---\n");
        markdown.append("创建时间: ").append(note.getCreatedAt().format(formatter)).append("\n");
        markdown.append("更新时间: ").append(note.getUpdatedAt().format(formatter)).append("\n");
        if (note.getIsFavorite()) {
            markdown.append("收藏: 是\n");
        }
        markdown.append("---\n\n");

        // 添加内容
        String content = note.getMarkdownContent();
        if (content == null || content.trim().isEmpty()) {
            content = note.getContent();
        }

        if (content != null && !content.trim().isEmpty()) {
            markdown.append(content);
        } else {
            markdown.append("*此便签暂无内容*");
        }

        // 添加导出信息
        markdown.append("\n\n---\n");
        markdown.append("*导出时间: ").append(LocalDateTime.now().format(formatter)).append("*\n");
        markdown.append("*导出自: RickPan 云盘系统*");

        String result = markdown.toString();
        log.info("导出Markdown完成: noteId={}, contentLength={}", noteId, result.length());

        return result;
    }
}
